# The shell that automates resetting, building, installation, and mounting
#  of DEFY
# reset: unmounts the disk, removes the module, and clears the data from
#         the mtd device
# build: unmounts the disk, ensures the module and mtd devices are installed,
#         and recompiles the module.  It does not mount the disk.
# install: same as build, but mounts the disk
# none: does not build the module but simply mounts the disk

modprobe mtd
modprobe mtdblock
modprobe nandsim cache_file=nand_file.img first_id_byte=0x20 second_id_byte=0xa2 third_id_byte=0x00 fourth_id_byte=0x15

if [[ $1 == "reset" ]]
then
    echo " Resetting..."
    umount /mnt/nandyaffs 2> /dev/null
    rmmod yaffs2multi.ko 2> /dev/null
    flash_erase /dev/mtd0 0 0 1> /dev/null
    rmmod nandsim
    rmmod mtdblock
    rmmod mtdchar
    rmmod nand
    rmmod mtd_blkdevs
    rmmod mtd
fi

if [[ $1 == "build" ]] || [[ $2 == "build" ]]
then
    echo " Preparing..."
    if [ ! -e /dev/mtd0 ]
    then
	modprobe mtd
	modprobe mtdblock
	modprobe nandsim first_id_byte=0x20 second_id_byte=0xa2 third_id_byte=0x00 fourth_id_byte=0x15
    fi
    umount /mnt/nandyaffs 2> /dev/null
    rmmod yaffs2multi.ko 2> /dev/null
    set +e
    echo " Cleaning..."
    rm *~ 2> /dev/null
    rm *# 2> /dev/null
    set -e
    echo " Building..."
#    make YAFFS_CURRENT=1 -s
    make -s
    echo " Installing..."
    make -s mi
    set +e
fi

if [[ $# -eq 0 ]] || [[ $2 == "launch" ]] || [[ $3 == "launch" ]]
then  
    echo " Mounting..."
    
    if [ ! -e /dev/mtd0 ]
    then
	echo " Creating Simulated Disk..."
	modprobe mtd
	modprobe mtdblock
	modprobe nandsim first_id_byte=0x20 second_id_byte=0xa2 third_id_byte=0x00 fourth_id_byte=0x15
    fi

    args="-o defy"
    
    umount /mnt/nandyaffs 2> /dev/null
    modprobe yaffs2multi
    mount -t yaffs2 $args /dev/mtdblock0 /mnt/nandyaffs
    if [ $? -ne 0 ]
    then
	echo " Error on mount"
    else
	echo " Mount successfull"
    fi
fi